package com.lnsf.dao.impl;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import com.lnsf.dao.IFinanceDao;
import com.lnsf.dbutils.DataAccess;
import com.lnsf.model.Finance;

public class FinanceDaoImpl implements IFinanceDao {

	@Override
	public List<Finance> select() {
		List<Finance> list = new ArrayList<Finance>();
		Connection conn = null;
		PreparedStatement prep = null;
		ResultSet rs = null;
		try {
			conn = DataAccess.getConnection();
			prep = conn.prepareStatement("select * from finance");
			rs = prep.executeQuery();
			while (rs.next()) {
				Finance finance = new Finance(rs.getInt(1), rs.getInt(2), rs.getInt(3), rs.getFloat(4));
				list.add(finance);
			}
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			DataAccess.closeConnection(rs, prep, conn);
		}
		return list;
	}

	@Override
	public int insert(Finance finance) {
		int flag = 0;
		Connection conn = null;
		PreparedStatement prep = null;
		try {
			conn = DataAccess.getConnection();
			prep = conn.prepareStatement("insert into finance values (null, ?, ?, ?)");
			prep.setInt(1, finance.getgId());
			prep.setInt(2, finance.getShId());
			prep.setFloat(3, finance.getTotalPrice());
			prep.execute();
			flag = 1;
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			DataAccess.closeConnection(prep, conn);
		}
		return flag;
	}

	@Override
	public int update(Finance finance) {
		int flag = 0;
		Connection conn = null;
		PreparedStatement prep = null;
		try {
			conn = DataAccess.getConnection();
			prep = conn.prepareStatement("update finance set gId = ?,shId=?, totalPrice=? where fId = ?");
			prep.setInt(1, finance.getgId());
			prep.setInt(2, finance.getShId());
			prep.setFloat(3, finance.getTotalPrice());
			prep.setInt(4, finance.getfId());
			prep.execute();
			flag = 1;
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			DataAccess.closeConnection(prep, conn);
		}
		return flag;
	}

	@Override
	public int delete(Finance finance) {
		int flag = 0;
		Connection conn = null;
		PreparedStatement prep = null;
		try {
			conn = DataAccess.getConnection();
			prep = conn.prepareStatement("delete from users where fId = ?");
			prep.setInt(1, finance.getfId());
			prep.execute();
			flag = 1;
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			DataAccess.closeConnection(prep, conn);
		}
		return flag;
	}

}
